package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ValidateException;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IUserRegisterService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotEmpty;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author : qj
 * @since: 2022/10/25  20:44
 */

@Component
@Slf4j
@ConfigurationProperties(prefix = "email")
@Data
public class IUserRegisterServiceImpl implements IUserRegisterService {

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private UserVerifyMapper userVerifyMapper;
    @Autowired
    private JavaMailSender mailSender;

    String subject;
    String textFrom;
    String text;

    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        UserRegisterResponse response = new UserRegisterResponse();
        //判空验证
        request.requestCheck();
        //验证用户名是否重复
        validUserNameRepeat(request);
        //1. 向⽤户表中插⼊⼀条记录
        Member member = new Member();
        member.setUsername(request.getUserName());
        member.setEmail(request.getEmail());
        //password 要加密处理
        String userpassword = DigestUtils.md5DigestAsHex(request.getUserPwd().getBytes());
        member.setPassword(userpassword);

        member.setCreated(new Date());
        member.setUpdated(new Date());
        member.setIsVerified("N");
        member.setState(1);

        int effectRows = memberMapper.insert(member);
        if (effectRows != 1){
            response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
            return response;
        }
        //2. 向⽤户验证表中插⼊⼀条记录
        UserVerify userVerify = new UserVerify();
        userVerify.setUsername(member.getUsername());
        String key = member.getUsername()+member.getPassword()+UUID.randomUUID().toString();
        String uuid = DigestUtils.md5DigestAsHex(key.getBytes());
        userVerify.setUuid(uuid);
        userVerify.setRegisterDate(new Date());
        userVerify.setIsExpire("N");
        userVerify.setIsVerify("N");
        int rows = userVerifyMapper.insert(userVerify);
        if (rows != 1){
            response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
            response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
            return response;
        }

        //3. 发送⽤户激活邮件
        //TODO 发送⽤户激活邮件 激活邮件应该是一个链接 有一个接口去处理我们的用户激活
        new Thread(() -> sendEamil(uuid,request)).start();
        
        //sendEamil(uuid,request);

        //打印日志
        log.info("用户注册成功，注册参数request:{}",JSON.toJSONString(request));
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }

    /**
     * 发送用户激活邮件
     * @param uuid
     * @param request
     * @return void
     * @author qj
     * @since 2022/10/26 15:38
     */
    private void sendEamil(String uuid, UserRegisterRequest request) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject(subject);
        message.setFrom(textFrom);
        message.setTo(request.getEmail());
        // StringBuilder stringBuilder = new StringBuilder();
        // stringBuilder.append("http://localhost:8099/user/verify?uid=").append(uuid).append("&username=").append(request.getUserName())
        String text = String.format(this.text, request.getUserName(), uuid);
        message.setText(text);
        mailSender.send(message);
    }

    //验证用户名是否重复
    private void validUserNameRepeat(UserRegisterRequest request) {
        Example example = new Example(Member.class);
        example.createCriteria()
                .andEqualTo("username",request.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(members)){
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }

    /**
    * @Description 用户注册激活
    * @Author Yi
    * @Date 2022/10/27 12:01
    */
    @Override
    public void verify(UserVerifyRequest request) {
        @NotEmpty String username = request.getUsername();
        @NotEmpty String uuid = request.getUuid();

        Example example = new Example(UserVerify.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("uuid", uuid);
        criteria.andEqualTo("username", username);
        criteria.andEqualTo("isExpire", "N");

        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);

        if (userVerifies.size() != 0) {
            Example memberExample = new Example(Member.class);
            memberExample.createCriteria()
                    .andEqualTo("username", username);
            List<Member> members = memberMapper.selectByExample(memberExample);
            if (members.size() != 0) {
                // 修改member表
                Long id = members.get(0).getId();
                Member member = new Member();
                member.setId(id);
                member.setIsVerified("Y");
                memberMapper.updateByPrimaryKeySelective(member);
                // 修改user_verify表
                Long verifyId = userVerifies.get(0).getId();
                UserVerify userVerify = new UserVerify();
                userVerify.setId(verifyId);
                userVerify.setIsVerify("Y");
                userVerifyMapper.updateByPrimaryKeySelective(userVerify);
            }
        }

    }
}
